#!/bin/bash
SPARK_DOWNLOAD_SERVER_URL="https://d.spark-app.store/"
SPARK_DOWNLOAD_SERVER_URL_NO_PROTOCOL="d.spark-app.store"
source /opt/durapps/spark-store/bin/bashimport/transhell.amber

load_transhell_debug
export DEBIAN_FRONTEND=noninteractive

trap 'unlock_file $DEBPATH' EXIT
case $(arch) in
   x86_64)
	STORE_URL="store"
	;;
   aarch64)
	STORE_URL="aarch64-store"
	;;
   loongarch64)
   	STORE_URL="loong64-store"
   	STORE_LIST_URL="-loong64"
   	;;
esac

echo "Spark Store Install script. 星火商店安装脚本"

function pkexec_as_current_user() {
    local user=$(who | awk '{print $1}' | head -n 1)
    local uid=$(id -u "$user")
    sudo -u "$user" DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/"$uid"/bus pkexec "$@"
}
function create_desktop_file() {
	local user=$(who | awk '{print $1}' | head -n 1)
	if [ -e $(sudo -u "$user" xdg-user-dir)/.config/spark-union/spark-store/ssshell-config-do-not-create-desktop ];then
	echo "It is configured that do not create desktop file. Give up"
	else
	exec_create_desktop_file
	fi
}
function exec_create_desktop_file() {
    local user=$(who | awk '{print $1}' | head -n 1)
    for desktop_file_path in $(dpkg -L "$package_name" |grep /usr/share/applications/ | awk '/\.desktop$/ {print}'); do
	if [ "$(cat $desktop_file_path | grep NoDisplay=true)" = "" ];then
	echo $desktop_file_path is checked and will be installed to desktop
        sudo -u "$user" cp "$desktop_file_path" "$(sudo -u "$user" xdg-user-dir DESKTOP)/"
	fi
    done
	for desktop_file_path in $(dpkg -L "$package_name" |grep /opt/apps/$package_name/entries/applications | awk '/\.desktop$/ {print}'); do
	if [ "$(cat $desktop_file_path | grep NoDisplay=true)" = "" ];then
	echo $desktop_file_path is checked and will be installed to desktop
        chmod +x $desktop_file_path
        sudo -u "$user" cp "$desktop_file_path" "$(sudo -u "$user" xdg-user-dir DESKTOP)/"
	fi
    done


}


function zenity() {
    local user=$(who | awk '{print $1}' | head -n 1)
    local uid=$(id -u "$user")
    sudo -u "$user" DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/"$uid"/bus zenity "$@"
}

function hash_check() {
    if [ ! -e "/var/lib/aptss/lists/${SPARK_DOWNLOAD_SERVER_URL_NO_PROTOCOL}_${STORE_URL}_Packages" ] && \
       [ ! -e "/var/lib/aptss/lists/d.store.deepinos.org.cn_${STORE_URL}_Packages" ] && \
       [ ! -e "/var/lib/aptss/lists/mirrors.sdu.edu.cn_spark-store_${STORE_URL}_Packages" ]; then
        echo "接收星火仓库软件信息中..."
        aptss ssupdate
    fi

    if [ -e "/var/lib/aptss/lists/${SPARK_DOWNLOAD_SERVER_URL_NO_PROTOCOL}_${STORE_URL}_Packages" ]; then
        PACKAGES_DATA_PATH="/var/lib/aptss/lists/${SPARK_DOWNLOAD_SERVER_URL_NO_PROTOCOL}_${STORE_URL}_Packages"
        echo "星火仓库的Packages位置为 $PACKAGES_DATA_PATH，是星火域名仓库配置"
    elif [ -e "/var/lib/aptss/lists/d.store.deepinos.org.cn_${STORE_URL}_Packages" ]; then
        PACKAGES_DATA_PATH="/var/lib/aptss/lists/d.store.deepinos.org.cn_${STORE_URL}_Packages"
        echo "星火仓库的Packages位置为 $PACKAGES_DATA_PATH，是d域名单目录仓库配置"
    else
        PACKAGES_DATA_PATH="/var/lib/aptss/lists/mirrors.sdu.edu.cn_spark-store-repository_${STORE_URL}_Packages"
        echo "星火仓库的Packages位置为 $PACKAGES_DATA_PATH，是SDU镜像仓库配置"
    fi

    echo "正在运行包验证..."
    echo "Running Spark Package Verify..."

    DEB_SHA512SUM=$(sha512sum "$1" | cut -d ' ' -f 1)
    unset IS_SHA512SUM_CHECKED
    IS_SHA512SUM_CHECKED=$(cat "$PACKAGES_DATA_PATH" | grep "$DEB_SHA512SUM")
}

function lock_file(){
chattr +i "$1"
}

function unlock_file(){
chattr -i "$1"
}

function ensure_aptss_exist(){

    if command -v aptss &>/dev/null; then
        aptss update
    else
        local deb_file="/tmp/spark-store-console-in-container_latest_all.deb"
        
        # Download package
        if ! wget -O "$deb_file" "https://amber-ce-resource.spark-app.store/store/depends/spark-store-console-in-container_latest_all.deb"; then
            echo "下载 .deb 安装包失败" >&2
            return 1
        fi

        # Install package
        if ! apt install -y "$deb_file"; then
            echo "安装 .deb 包失败" >&2
            rm -f "$deb_file"
            return 1
        fi
        rm -f "$deb_file"

        # Verify installation
        if ! command -v aptss &>/dev/null; then
            echo "成功安装但未找到 aptss 命令" >&2
            return 1
        fi
    fi
}
export -f ensure_aptss_exist
####################################

if [ $# -eq 0 ]; then
    echo "没有接收到参数，退出"
    echo "用法：$0 deb路径"
    echo "OMG-IT-GOES-WRONG"
    exit
fi



if [ "$(id -u)" != "0" ]; then
    echo "${TRANSHELL_CONTENT_PLEASE_RUN_AS_ROOT}"
    echo "OMG-IT-GOES-WRONG"
    exit 1
fi

if [ ! -f "$1" ]; then
    echo "${TRANSHELL_CONTENT_FILE_NOT_EXIST},Trying to redownload"
    FILEPATH=$(dirname "$1")
    FILENAME=$(basename "$1")
    PACKAGE_NAME=$(echo "$FILENAME" | sed -r 's/^([^_]+)_.*$/\1/')
    VERSION=$(echo "$FILENAME" | sed -r 's/^[^_]+_([^_]+)_.*$/\1/')
    pushd ${FILEPATH}
    aptss download ${PACKAGE_NAME}
    popd
    if [ ! -f "$1" ]; then
    	echo "OMG-IT-GOES-WRONG"
    	exit 1
    else
    	DEBPATH=$(realpath "$1")
    fi
    else
    DEBPATH=$(realpath "$1")
fi

lock_file "$DEBPATH"

hash_check "$DEBPATH"

if [ -z "$IS_SHA512SUM_CHECKED" ]; then
    echo "尝试更新仓库信息重新校验"
    aptss ssupdate
    hash_check "$DEBPATH"
	if [ -z "$IS_SHA512SUM_CHECKED" ]; then
	echo -e "$TRANSHELL_CONTENT_HASH_CHECK_FAILED"
	zenity --info --icon-name=spark-store --height 270 --width 500 --text "$TRANSHELL_CONTENT_HASH_CHECK_FAILED"
	echo  "OMG-IT-GOES-WRONG"
	exit 1
	fi
fi

if [ ! -z "$IS_SHA512SUM_CHECKED" ]; then
    echo "校验成功，开始安装"
    echo "----------------------------------------------------------------------------------"
package_name=$(dpkg-deb -f "$DEBPATH" Package)
echo "Package name is $package_name"
try_run_output=$(/opt/durapps/spark-store/bin/update-upgrade/ss-do-upgrade-worker.sh test-install-app "$DEBPATH")
try_run_ret="$?"
# 安装失败后进行 aptss 刷新，随后尝试在主机安装
if [ "$try_run_ret" -ne 0 ]; then
    aptss update
    try_run_output=$(/opt/durapps/spark-store/bin/update-upgrade/ss-do-upgrade-worker.sh test-install-app "$DEBPATH")
    try_run_ret="$?"
fi

if [ "$try_run_ret" -ne 0 ]; then ## 若安装检测仍然失败
    if [[ "$IS_ACE_ENV" == "" ]];then ## 如果未在ACE环境中
        # 定义按顺序尝试的ACE环境（命令:推荐安装包）
        declare -a ace_commands_order=(
            "bookworm-run:amber-ce-bookworm"
            "trixie-run:amber-ce-trixie"
            "deepin23-run:amber-ce-deepin23"
        )
        
        success=false
        recommendation_msg=""
        # 收集所有推荐信息
        for ace_entry in "${ace_commands_order[@]}"; do
            recommendation_msg+="您可安装 ${ace_entry%%:*} 兼容环境后重试: ${ace_entry#*:}\n"
        done

        # 按顺序尝试每个ACE环境
        for ace_entry in "${ace_commands_order[@]}"; do
            ace_cmd=${ace_entry%%:*}
            if command -v "$ace_cmd" >/dev/null 2>&1; then
                echo "----------------------------------------"
                echo "正在尝试使用 $ace_cmd 环境安装..."
                echo "----------------------------------------"
                
                # 在ACE环境中执行安装检测
                $ace_cmd ensure_aptss_exist
                try_run_output=$($ace_cmd aptss install --dry-run "$DEBPATH" 2>&1)
                try_run_ret="$?"
                
                # 如果首次检测失败则更新后重试
                if [ "$try_run_ret" -ne 0 ]; then
                    $ace_cmd aptss update
                    try_run_output=$($ace_cmd aptss install --dry-run "$DEBPATH" 2>&1)
                    try_run_ret="$?"
                fi

                # 最终检测结果处理
                if [ "$try_run_ret" -eq 0 ]; then
                    echo "----------------------------------------"
                    echo "在 $ace_cmd 环境中预检成功，开始安装..."
                    echo "----------------------------------------"
                    $ace_cmd 'dpkg -i "$DEBPATH" || aptss install "$DEBPATH" -yfq'
                    success=true
                    break # 跳出循环
                else
                    echo "----------------------------------------"
                    echo "在 $ace_cmd 环境中安装预检失败，错误信息："
                    echo -e "${try_run_output}"
                    echo "----------------------------------------"
                fi
            fi
        done

        if ! $success; then
            echo "OMG-IT-GOES-WRONG"
            echo -e "${try_run_output}"
            echo -e "所有ACE环境尝试失败，推荐安装以下任一兼容环境:\n${recommendation_msg}"
            exit "$try_run_ret"
        fi
    else # 已经在ACE环境中仍失败直接退出
        echo "OMG-IT-GOES-WRONG"
        echo -e "${try_run_output}"
        exit "$try_run_ret"
    fi
else ## 如果主机安装检测成功
    dpkg -i "$DEBPATH" || aptss install "$DEBPATH" -yfq
fi

### 退出阶段保持不变 ###
if [ "$?" = "0" ] && [ "$2" = "--delete-after-install" ]; then
    if dpkg -s "$package_name" >/dev/null 2>&1; then
        echo "软件包已安装：$package_name"
        create_desktop_file
        unlock_file $DEBPATH
        rm "$DEBPATH"
        echo "${TRANSHELL_CONTENT_DEB_IS_DELETED}"
    else
        echo "软件包未安装：$package_name"
        echo "安装异常！抛出错误"
        echo "OMG-IT-GOES-WRONG"
    fi
else
    echo "${TRANSHELL_CONTENT_WILL_NOT_DELETE_DEB}"
    if dpkg -s "$package_name" >/dev/null 2>&1; then
        echo "软件包已安装：$package_name"
        create_desktop_file
    else
        echo "软件包未安装：$package_name"
        echo "安装异常！抛出错误"
        echo "OMG-IT-GOES-WRONG"
    fi
fi
fi
